package com.qfmy.web.interactor;

import com.qfmy.web.enmu.ResultCode;
import com.qfmy.web.exception.BaseException;
import com.qfmy.web.utils.JwtUtil;
import com.qfmy.web.utils.LoginUserHolder;
import io.jsonwebtoken.Claims;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author: 廖志伟
 * @date: 2024-11-28
 * @description: 登录拦截器
 */

@SuppressWarnings("all")
public  class LoginInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截器的业务逻辑
        //获取token
        String accessToken = request.getHeader("access_token");
        //判断token是否为空
        if(accessToken == null || accessToken.equals("")){
            throw new BaseException(ResultCode.TOKEN_NOT_FOUND);
        }

        //解析token
       try {
           Claims claims = JwtUtil.parseToken(accessToken);

           //获取将token存放在当前线程
           LoginUserHolder.setLoginUser(claims);
           //放行
           return true;
       }catch (Exception e){
           response.setStatus(401);
           return false;
       }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //销毁资源

    }
}
